<!--
 * @Author: chenhuanhuan 2925102113@qq.com
 * @Date: 2024-12-12 16:41:13
 * @LastEditors: chenhuanhuan 2925102113@qq.com
 * @LastEditTime: 2025-02-20 10:24:35
 * @FilePath: \hbzc-groupmeal-center-web\src\centerViews\basicInformation\spuManage\spuInformation\components\addModifPop.vue
-->
<template>
  <pb-popup v-model="isShow" :title="`${spuForm.spuId ? '修改' : '添加'}SPU`" @cancelFn="offPopup" @confirmFn="onSave">

    <div v-loading="loading">
      <el-form style="width: 100%" :model="spuForm" label-width="auto" inline ref="ruleFormRef1" :rules="rules"
        validate-on-rule-change>
        <div style="width: 100%" class="flex">
          <el-form-item label="SPU编码：" style="width: 200px">
            {{ spuForm.spuCode }}
          </el-form-item>
          <el-form-item label="助记码：" prop="mnemonicCode">
            <div v-if="!innerVisible">
              <span>
                {{ spuForm.mnemonicCode }}
              </span>
              <pb-icon name="edit" v-show="spuForm.mnemonicCode && spuForm.isSystemData != 1" color="rgba(0,0,0,0.25)"
                class="ml-2" @click="innerVisible = true"></pb-icon>
            </div>
            <pb-input v-model.trim="spuForm.mnemonicCode" maxlength="50" v-else @blur="CheckMnemonic"></pb-input>

          </el-form-item>
        </div>
      </el-form>
      <el-form style="width: 100%" :model="spuForm" label-width="auto" inline label-position="top" ref="ruleFormRef"
        :rules="rules" validate-on-rule-change>

        <el-form-item label="SPU类别" prop="spuClassCode" v-if="!spuForm.spuId">
          <el-select v-model="spuForm.spuClassCode" placeholder="请选择" style="width: 240px" filterable>
            <el-option-group v-for="group in treeData" :key="group.spuClassCode" :label="group.spuClassName">
              <el-option v-for="item in group.children" :key="item.spuClassCode" :label="item.spuClassName"
                :value="item.spuClassCode" />
            </el-option-group>
          </el-select>
        </el-form-item>
        <el-form-item label="SPU类别" prop="spuClassName" v-else>
          <pb-input v-model.trim="spuForm.spuClassName" placeholder="请输入SPU名称" :disabled="true" @change="changeName"
            maxlength="10"></pb-input>
        </el-form-item>
        <el-form-item label="SPU名称" prop="spuName">
          <pb-input v-model.trim="spuForm.spuName" placeholder="请输入SPU名称" :disabled="spuForm.isSystemData"
            @change="changeName" maxlength="10"></pb-input>
        </el-form-item>
        <el-form-item label="出成率(%)" style="margin: 0" prop="recoveryRate">
          <pb-input v-model.trim="spuForm.recoveryRate" placeholder="请输入出成率"
            :disabled="spuForm.isSystemData"></pb-input>
        </el-form-item>
        <el-form-item label="别名" style="width: 100%; margin: 0">
          <div class="name-tag-box">
            <div class="common-name">
              <span class="common">常用名：</span>
              <span class="name" v-if="spuForm.commonlyName">
                {{ spuForm.commonlyName }}
              </span>
            </div>
            <CreateTag :defaultVal="spuForm.spuName" :tagsList="commonList" @setTag="setCommon" @delTag="delCommon"
              @addTag="addCommon"></CreateTag>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </pb-popup>
</template>

<script setup lang="ts">
import { upperLetter } from "@/utils/upperLetter";
import { addSpuInfo, setSpuInfo, getSpuCode, getCheckSpuName, getSpuClassList } from "@/api/Spu";
import { createMessage } from "@/Public-UIlibrary/pb-message/method";
import { getSpuClassTreeApi } from "@/utils/globalFn";

const emits = defineEmits(['refresh'])
const isShow = ref(false);
const innerVisible = ref(false);
const loading = ref(false);

const treeData = ref(null)

const formOrigin = () => ({
  spuId: null,
  spuCode: "",
  spuName: "",
  spuAlias: "",
  spuClassCode: "",
  spuClassName: "",
  recoveryRate: 100,
  commonlyName: "",
  mnemonicCode: "",
  pic: "",
});

// 别名列表
const commonList = ref([]);

let spuForm = ref(formOrigin());

const rules = reactive({
  spuClassCode: [
    { required: true, message: "此项必填", trigger: ["blur",] },
  ],
  mnemonicCode: [
    { pattern: /^[A-Z0-9]{1,50}$/, message: "最多包含1-50位大写字母和数字", trigger: ["blur", "change"] },
  ],
  spuName: [{ required: true, message: "此项必填", trigger: ["blur",], },

  {
    pattern: /^[\u4E00-\u9FA5A-Za-z0-9]{1,10}$/,
    message: "最多包含1-10位数字、字母和中文",
    trigger: ["blur", "change"],
  },
  {
    validator(rule, value, callback) {
      checkName(value).then(res => {
        if (res) {
          return callback('SPU名称已存在')
        } else {
          callback()
        }
      })
    }
  }
  ],
  recoveryRate: [
    {
      required: false,
      pattern: /^(100|[1-9][0-9]?)$/,
      message: "必须为1-100的整数",
      trigger: ["blur", "change"]
    },
  ],
});

const showFn = (data) => {
  let { info, code } = data
  if (info) {
    spuForm.value = info
    commonList.value = info.spuAlias ? info.spuAlias.split('、') : []
  } else {
    getSpuClassTreeApi().then(res => {
      treeData.value = res
      if (code) spuForm.value.spuClassCode = code
    })
  }
  isShow.value = true;
};


watch(
  () => spuForm.value.spuClassCode,
  (val) => {
    if (isShow.value && !spuForm.value.spuId) {
      getSpuCode({ spuClassCode: val }).then(res => {
        if (res.code == 2000) {
          spuForm.value.spuCode = res.data.spuCode
        }
      })
    }
  }
)

// spu名称改变时生成助记码
const changeName = (val: string) => {
  spuForm.value.mnemonicCode = upperLetter(val);
  spuForm.value.commonlyName = val;
};

const CheckMnemonic = (val) => {
  let reg = /^(?![0-9]+$)[A-Z0-9]{1,10}$/
  if (reg.test(val)) {
    innerVisible.value = false
  }
}


// 检查spu是否已存在
const checkName = (val: string) => {
  return new Promise<void>((resolve, reject) => {
    let spuId = spuForm.value.spuId ? spuForm.value.spuId : null
    getCheckSpuName({ spuName: val, spuId }).then(res => {
      if (res.code == 2000) {
        if (res.data.spuNameExist) {
          resolve(true)
        } else {
          resolve(false)
        }
      }
    })
  })
}



// 设置常用名
const setCommon = (val: string) => {
  spuForm.value.commonlyName = val;
};

// 删除常用名 ,删除项若是正在使用的则恢复成spu名称
const delCommon = (idx: number, val: string) => {
  commonList.value.splice(idx, 1);
  if (val == spuForm.value.commonlyName) {
    spuForm.value.commonlyName = spuForm.value.spuName;
  }
};

// 添加常用名
const addCommon = (val: string) => {
  commonList.value.push(val);
};

const ruleFormRef = ref(null);
const ruleFormRef1 = ref(null);
const onSave = async () => {
  Promise.all([ruleFormRef1.value.validate(), ruleFormRef.value.validate()]).then(res => {
    if (spuForm.value.spuId) {
      setSpuInfoApi()
    } else {
      addSpuInfoApi()
    }
  })

};

// 添加
const addSpuInfoApi = () => {
  loading.value = true
  return new Promise<void>((resolve, reject) => {
    spuForm.value.recoveryRate = spuForm.value.recoveryRate ? spuForm.value.recoveryRate : 100
    spuForm.value.spuAlias = commonList.value.join('、')
    delete spuForm.value.spuId
    addSpuInfo(spuForm.value).then(res => {
      loading.value = false
      if (res.code == 2000) {
        createMessage({
          message: '添加成功'
        })
        isShow.value = false
        emits("refresh")
      }
    })
  })
}
// 修改
const setSpuInfoApi = () => {
  loading.value = true
  return new Promise<void>((resolve, reject) => {
    let { spuId, commonlyName, pic, spuName, mnemonicCode } = { ...spuForm.value }
    let spuAlias = commonList.value.join('、')
    let recoveryRate = spuForm.value.recoveryRate ? spuForm.value.recoveryRate : 100
    setSpuInfo({
      spuId, commonlyName, recoveryRate, pic, spuAlias, spuName, mnemonicCode
    }).then(res => {
      loading.value = false
      if (res.code == 2000) {
        createMessage({
          message: '编辑成功'
        })
        isShow.value = false
        emits("refresh")
      }
    })
  })
}

// 关闭弹窗重置表单
const offPopup = () => {
  ruleFormRef.value.resetFields();
  ruleFormRef1.value.resetFields();
  spuForm.value = formOrigin();
  commonList.value = [];
  innerVisible.value = false
};

defineExpose({ showFn });
</script>

<style lang="scss" scoped>
::v-deep .el-select__wrapper {
  min-height: 36px !important;
  padding: 1px 16px !important;
}

.el-select-group__wrap {
  margin-bottom: 8px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.15);
}

.name-tag-box {
  width: 98%;
  padding: 8px 12px;
  background: #ffffff;
  border-radius: 4px;
  border: 1px solid rgba(0, 0, 0, 0.15);

  .common-name {
    font-family:
      PingFang SC,
      PingFang SC;
    font-weight: 400;

    .common {
      font-size: 16px;
      color: rgba(0, 0, 0, 0.65);
      line-height: 24px;
    }

    .name {
      padding: 2px 8px;
      background: #ffffff;
      border-radius: 4px;
      border: 1px solid var(--pb-color-primary);
      font-size: 14px;
      color: var(--pb-color-primary);
      line-height: 22px;
      text-align: center;
    }
  }
}
</style>